//解析结果返回

import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:get/utils.dart';
import 'package:palmf_hid/common/apis/api.dart';
import 'package:palmf_hid/common/entities/response/curve_entity.dart';
import 'package:palmf_hid/common/entities/response/lot_sample_entity.dart';
import 'package:palmf_hid/common/utils/order_util/common_order_util.dart';
import 'package:palmf_hid/common/utils/order_util/order_utils.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/common/values/conf.dart';
import 'package:palmf_hid/common/values/error_code.dart';
import 'package:palmf_hid/pages/main/main_logic.dart';

//解析测试结果
Map<String, dynamic> readResultBack(List<int> data) {
  Map<String, dynamic> map = {};
  //结果字节高位在前反转
  double resultDouble =
      getFloatFromIntBits(intArrToHex(data.sublist(0, 4).reversed.toList()));
  map["result"] = resultDouble;
  map["saveNum"] = data.sublist(4, 5)[0];
  double referLower =
      getFloatFromIntBits(intArrToHex(data.sublist(5, 9).reversed.toList()));
  map["referLower"] = referLower.toString().trim();
  double referUpper =
      getFloatFromIntBits(intArrToHex(data.sublist(9, 13).reversed.toList()));
  map["referUpper"] = referUpper.toString().trim();
  int arrow = data.sublist(13, 14)[0];
  map["project"] =
      readProject(intArrToHex(data.sublist(14, 24)).toUpperCase()).trim();
  map["resultUnit"] =
      hexToAscii(intArrToHex(data.sublist(24, 32)).toUpperCase()).trim();

  map["patientId"] = int.parse(intArrToHex(data.sublist(34, 36)), radix: 16);

  map["sample"] = data.sublist(36, 37)[0];
  int franBack = data.sublist(37, 38)[0];
  String resultDisplay = "";
  if (arrow == 0) {
    resultDisplay = "↓";
  } else if (arrow == 1) {
    resultDisplay = "↑";
  } else {
    if (franBack == 1) {
      resultDisplay = "<";
    } else if (franBack == 2) {
      resultDisplay = ">";
    }
  }
  map["curveVersion"] = data.sublist(45, 46)[0];
  String lotNum = radixToString(data.sublist(46, 56)).toString().trim();
  String batchNo = MyRegUtil.isNumAndLetter(lotNum) ? lotNum : "";
  map["curveBatchNoFromPalmf"] = batchNo;
  map["resultDisplay"] = resultDisplay;
  map["deviceTime"] = data.sublist(data.length - 8, data.length - 2);
  map["jointInspectionNo"] = data[data.length - 2];
  map["jointInspectionNum"] = data[data.length - 1];
  MyLogUtil().i(map);
  return map;
}

//项目名称
readProject(String data) {
  String result = hexToAscii(data
          .replaceAll(REF, TEMP_CHAR_REF)
          .replaceAll(BT, TEMP_CHAR_BT)
          .replaceAll(SYNC_BT, TEMP_CHAR_BT)
          .replaceAll(SYNC_REF, TEMP_CHAR_REF))
      .replaceAll(" ", "")
      .replaceAll(TEMP_CHAR_REF_CN, REF_STR)
      .replaceAll(TEMP_CHAR_BT_CN, BT_STR);
  return result;
}

//试剂卡信息解析
void readCardList(
    List<int> backIntValue,
    String deviceNum,
    Map<String, Map<String, dynamic>> regentCardWaitUpdateMap,
    MainLogic logic) {
  if (sumCheck(backIntValue.sublist(3))) {
    LotSampleEntity lotSampleEntity = parseLotSampleInfo(backIntValue);
    if (!MyRegUtil.isNumAndLetter(lotSampleEntity.lotNum.toString().trim())) {
      return;
    }
    lotSampleEntity.deviceNum = deviceNum;
// 第18、19字节为总条数和顺序条数相等时，发送完成
    if (backIntValue[61] == 1) {
      regentCardWaitUpdateMap.clear();
    }
    if (null != lotSampleEntity.cardMark) {
      Map<String, dynamic> map = {};
      map["lotSampleEntityJson"] = jsonEncode(lotSampleEntity);
      regentCardWaitUpdateMap[lotSampleEntity.cardMark!] = map;
    }
    if (backIntValue[61] == backIntValue[62]) {
      //先处理最后一条数据
      MyLogUtil().i(regentCardWaitUpdateMap);
      getRegentParamFromNet(lotSampleEntity, regentCardWaitUpdateMap, logic);
    }
  } else {
    MyToastUtil.show(deviceNum + 'unknownMsg'.tr + getLotNumListCheckFail);
  }
}

//从网络获取曲线参数
void getRegentParamFromNet(
    LotSampleEntity lotSampleEntity,
    Map<String, Map<String, dynamic>> regentCardWaitUpdateMap,
    MainLogic logic) {
  ApiRepository.getCurve(lotSampleEntity.lotNum ?? "",
          lotSampleEntity.sampleType ?? "", lotSampleEntity.deviceNum ?? "")
      .then((value) {
    if (value.isNotEmpty) {
      if (regentCardWaitUpdateMap.containsKey(lotSampleEntity.cardMark)) {
        CurveEntity curveEntity = value[0];
        String curveParam =
            (curveEntity.curveParamsHex ?? "").replaceAll(";", ",");
        if (curveParam.isEmpty) {
          if (regentCardWaitUpdateMap.containsKey(lotSampleEntity.cardMark)) {
            regentCardWaitUpdateMap.remove(lotSampleEntity.cardMark);
            if (regentCardWaitUpdateMap.isEmpty) {
              MyLoadingUtil.hideLoading();
              MyToastUtil.show('ok'.tr);
            } else {
              LotSampleEntity lotSampleEntity = jsonDecode(
                  regentCardWaitUpdateMap[regentCardWaitUpdateMap.keys.first]![
                      "lotSampleEntityJson"]);
              getRegentParamFromNet(
                  lotSampleEntity, regentCardWaitUpdateMap, logic);
            }
          }
        } else {
          ///走这里的是从网络获取到了曲线参数信息，需要更新手持机的曲线参数
          Map<String, dynamic> map =
              regentCardWaitUpdateMap[lotSampleEntity.cardMark]!;
          map["curveParam"] = curveParam.split(",");
          regentCardWaitUpdateMap[lotSampleEntity.cardMark!] = map;
          //发送获取手持机曲线参数信息
          getRegentByLotNum(lotSampleEntity, logic);
        }
      }
    } else {
      if (regentCardWaitUpdateMap.containsKey(lotSampleEntity.cardMark)) {
        regentCardWaitUpdateMap.remove(lotSampleEntity.cardMark);
        if (regentCardWaitUpdateMap.isEmpty) {
          MyLoadingUtil.hideLoading();
          MyToastUtil.show('ok'.tr);
        } else {
          LotSampleEntity lotSampleEntity = LotSampleEntity.fromJson(jsonDecode(
              regentCardWaitUpdateMap[regentCardWaitUpdateMap.keys.first]![
                  "lotSampleEntityJson"]));
          getRegentParamFromNet(
              lotSampleEntity, regentCardWaitUpdateMap, logic);
          MyLogUtil().i(regentCardWaitUpdateMap);
        }
      }
    }
  }, onError: (e) {
    if (regentCardWaitUpdateMap.containsKey(lotSampleEntity.cardMark)) {
      regentCardWaitUpdateMap.remove(lotSampleEntity.cardMark);
      if (regentCardWaitUpdateMap.isEmpty) {
        MyLoadingUtil.hideLoading();
        MyToastUtil.show('ok'.tr);
      } else {
        LotSampleEntity lotSampleEntity = jsonDecode(regentCardWaitUpdateMap[
            regentCardWaitUpdateMap.keys.first]!["lotSampleEntityJson"]);
        getRegentParamFromNet(lotSampleEntity, regentCardWaitUpdateMap, logic);
        MyLogUtil().i(regentCardWaitUpdateMap);
      }
    }
  });
}

//获取某一试剂卡信息
void getRegentByLotNum(LotSampleEntity lotSampleEntity, MainLogic logic) {
  MyLogUtil().i("获取某一试剂卡信息 ${lotSampleEntity.toJson()}");
  //获取某一批号试剂信息
}

//解析试剂卡批次号和样本类型
LotSampleEntity parseLotSampleInfo(List<int> data) {
  data = data.sublist(3);
  LotSampleEntity entity = LotSampleEntity();
  //1字节试剂卡标识,数字
  entity.cardMark = data[0].toString();
  var batch = radixToString(data.sublist(1, 11));
  //10字节批号，ASCII
  entity.lotNum = batch.toString().trim();
  //1字节样本类型，0：全血1：血清 数字
  entity.sampleType = data[11].toString();
  //第18、19字节为总条数和顺序条数
  entity.totalNum = data[data.length - 2].toString();
  entity.orderNum = data[data.length - 3].toString();
  return entity;
}

//仪器编号
String readDeviceNo(List<int> data) {
  if (sumCheck(data.sublist(2))) {
    MyLogUtil().i(hex.encode(data).substring(6, 36));
    return hexToAscii(hex.encode(data).substring(6, 36)).trim();
  } else {
    return "";
  }
}

///收到手持机曲线参数信息
handleRegentParamInfoBack(
    List<int> backIntValue,
    Map<String, Map<String, dynamic>> regentCardWaitUpdateMap,
    MainLogic logic) {
  if (sumCheck(backIntValue.sublist(2))) {
    // if (backIntValue[61] == 1) {
    //   logic.cardMark = backIntValue[7].toString();
    //   if (regentCardWaitUpdateMap.containsKey(logic.cardMark)) {
    //     Map<String, dynamic> map = regentCardWaitUpdateMap[logic.cardMark]!;
    //     // 曲线参数原始数据
    //     map['regentParamOriginData'] =
    //         backIntValue.sublist(4, backIntValue.length - 3);
    //     regentCardWaitUpdateMap[logic.cardMark] = map;
    //     // MyLogUtil().i(regentCardWaitUpdateMap);
    //   }
    // } else if (backIntValue[61] == 4) {
    //   //曲线参数有4条数据,接受完成后替换参数，更新曲线；
    //   if (regentCardWaitUpdateMap.containsKey(logic.cardMark)) {
    //     Map<String, dynamic> map = regentCardWaitUpdateMap[logic.cardMark]!;
    //     if (map.containsKey("regentParamOriginData")) {
    //       map['regentParamOriginData'] = map['regentParamOriginData'] +
    //           backIntValue.sublist(4, backIntValue.length - 3);
    //       regentCardWaitUpdateMap[logic.cardMark] = map;
    //       MyLogUtil().i(regentCardWaitUpdateMap);
    //       MyLogUtil().i("==========${map['regentParamOriginData'].length}");
    //       //四条数据拼接完成（每条去掉头55AA，忽略字符39，第几条，总条数，合模校验  共6字节），开始更新曲线参数
    //       if (map['regentParamOriginData'].length == 228) {
    //
    //
    //       } else {
    //         if (regentCardWaitUpdateMap.isEmpty) {
    //           MyLoadingUtil.hideLoading();
    //           MyToastUtil.show('ok'.tr);
    //         } else {
    //           LotSampleEntity lotSampleEntity = jsonDecode(
    //               regentCardWaitUpdateMap[regentCardWaitUpdateMap.keys.first]![
    //                   "lotSampleEntityJson"]);
    //           getRegentParamFromNet(
    //               lotSampleEntity, regentCardWaitUpdateMap, logic);
    //         }
    //       }
    //     } else {
    //       if (regentCardWaitUpdateMap.isEmpty) {
    //         MyLoadingUtil.hideLoading();
    //         MyToastUtil.show('ok'.tr);
    //       } else {
    //         LotSampleEntity lotSampleEntity = jsonDecode(
    //             regentCardWaitUpdateMap[regentCardWaitUpdateMap.keys.first]![
    //                 "lotSampleEntityJson"]);
    //         getRegentParamFromNet(
    //             lotSampleEntity, regentCardWaitUpdateMap, logic);
    //       }
    //     }
    //   }
    // } else {
    //   if (regentCardWaitUpdateMap.containsKey(logic.cardMark)) {
    //     Map<String, dynamic> map = regentCardWaitUpdateMap[logic.cardMark]!;
    //     if (map.containsKey("regentParamOriginData")) {
    //       map['regentParamOriginData'] = map['regentParamOriginData'] +
    //           backIntValue.sublist(4, backIntValue.length - 3);
    //     } else {
    //       if (regentCardWaitUpdateMap.isEmpty) {
    //         MyLoadingUtil.hideLoading();
    //         MyToastUtil.show('ok'.tr);
    //       } else {
    //         LotSampleEntity lotSampleEntity = jsonDecode(
    //             regentCardWaitUpdateMap[regentCardWaitUpdateMap.keys.first]![
    //                 "lotSampleEntityJson"]);
    //         getRegentParamFromNet(
    //             lotSampleEntity, regentCardWaitUpdateMap, logic);
    //       }
    //     }
    //   }
    // }
  } else {
    if (regentCardWaitUpdateMap.isEmpty) {
      MyLoadingUtil.hideLoading();
      MyToastUtil.show('ok'.tr);
    } else {
      LotSampleEntity lotSampleEntity = jsonDecode(regentCardWaitUpdateMap[
          regentCardWaitUpdateMap.keys.first]!["lotSampleEntityJson"]);
      getRegentParamFromNet(lotSampleEntity, regentCardWaitUpdateMap, logic);
    }
  }
}
